package org.imyy.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 日志过滤器
 * 
 * @author Kvkens
 * 
 */
public class LogFilter implements Filter {
	private Log log = LogFactory.getLog(this.getClass());
	private String filterName;

	@Override
	public void init(FilterConfig config) throws ServletException {
		// TODO Auto-generated method stub
		filterName = config.getFilterName();
		log.info("启动Filter:" + filterName);
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest request = (HttpServletRequest)req;
		HttpServletResponse response = (HttpServletResponse)res;
		long startTime = System.currentTimeMillis();
		String requestURI = request.getRequestURI();
		requestURI = request.getQueryString() == null?requestURI:(requestURI + "?" + request.getQueryString());
		chain.doFilter(request, response);
		long endTime = System.currentTimeMillis();
		log.info(request.getRemoteAddr() + " 访问了 " + requestURI + ",总用时：" + (endTime-startTime) + " 毫秒");
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		log.info("关闭 Filter：" + filterName);
	}

}
